package nyist.media.service.impl;

import nyist.media.bean.admin.AdminInfoBean;
import nyist.media.bean.admin.AdminListBean;
import nyist.media.config.shiro.Principal;
import nyist.media.entity.admin.Admin;
import nyist.media.entity.admin.Log;
import nyist.media.entity.admin.MenuAuth;
import nyist.media.entity.admin.Role;
import nyist.media.exception.BusinessException;
import nyist.media.page.ApiResult;
import nyist.media.page.AppPage;
import nyist.media.repository.AdminRepository;
import nyist.media.repository.LogRepository;
import nyist.media.repository.RoleRepository;
import nyist.media.service.AdminService;
import nyist.media.utils.NetworkUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : dcf
 * @date : 2019/3/12
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private LogRepository logRepository;
    @Autowired
    private RoleRepository roleRepository;


    @Override
    public List<String> findAuthorities(Long id) {
        return adminRepository.findOne(id).getRoles().stream().map(Role::getAuths).flatMap(Collection::stream)
                .map(MenuAuth::getAuthority).filter(StringUtils::isNotEmpty).collect(Collectors.toList());
    }

    @Override
    public Admin getCurrent() {
        Principal principal = (Principal) SecurityUtils.getSubject().getPrincipal();
        if (!Objects.isNull(principal)) {
            return adminRepository.findOne(principal.getId());
        }
        return null;
    }

    @Override
    public AppPage<AdminListBean> findAdminList(PageRequest pageRequest, String keyword) {
        Page<Admin> page = adminRepository.findAdminList(pageRequest, keyword);
        List<AdminListBean> list = page.getContent().stream().map(AdminListBean::new).collect(Collectors.toList());
        return new AppPage<>(pageRequest, page.getTotalElements(), page.getTotalPages(), list);
    }

    @Override
    public Admin toggleEnabled(Long id) {
        Admin admin = adminRepository.findOne(id);
        if (admin.isEnabled()) {
            //禁用
            admin.setRoles(null);
        }
        admin.setEnabled(!admin.isEnabled());
        return adminRepository.save(admin);
    }

    @Override
    public List<Admin> findList() {
        Role repairRole = roleRepository.findByNameLike("%维修员%");
        return adminRepository.findAll().stream().filter(admin -> admin.getRoles().contains(repairRole)).collect(Collectors.toList());
    }

    @Override
    public AdminInfoBean getInfo(Long id) {
        return new AdminInfoBean(adminRepository.getOne(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AdminInfoBean param) {
        List<Role> roles = roleRepository.findAllByIdIn(Arrays.asList(param.getRoleIds()));
        if (roles.isEmpty()) {
            throw new BusinessException(ApiResult.ILLEGAL_PARAMS, "至少有一个角色");
        }
        Admin current = getCurrent();
        Admin a = adminRepository.findOne(param.getId());
        a.setLockIn(param.getLockIn());
        a.setEmail(param.getEmail());
        a.setName(param.getName());
        a.setModifyDate(new Date());
        a.setPhone(param.getPhone());
        // 更新密码
        this.updatePwd(a, param.getPwd(), current.getUsername());
        // 清除锁定时间
        if (a.getLockIn() != null && param.getLockIn() == null) {
            a.setFailCount(0);
        }
        a.setLockIn(param.getLockIn());
        a.setEnabled(param.isEnabled());
        a.setRoles(new HashSet<>(roles));
        adminRepository.save(a);
    }

    /**
     * 更新密码
     *
     * @param a        管理员
     * @param pwd      未加密的密码
     * @param operator 操作人
     */
    private void updatePwd(Admin a, String pwd, String operator) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        if (StringUtils.isNotEmpty(pwd)) {
            a.setPassword(DigestUtils.md5Hex(pwd.getBytes()));
            Log log = new Log();
            Date now = new Date();
            log.setOperation("修改" + a.getName() + "的登录密码");
            log.setCreateDate(now);
            log.setModifyDate(now);
            log.setParams("");
            log.setIp(NetworkUtil.getIpAddress(request));
            log.setOperator(operator);
            logRepository.save(log);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCurrent(AdminInfoBean param) throws BusinessException {
        Admin a = getCurrent();
        a.setName(param.getName());
        // 更新密码
        this.updatePwd(a, param.getPwd(), a.getUsername());
        adminRepository.save(a);
    }

    @Override
    public Admin findByUsername(String username) {
        return adminRepository.findByUsername(username).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(AdminInfoBean param) throws BusinessException {
        List<Role> roles = roleRepository.findAllByIdIn(Arrays.asList(param.getRoleIds()));
        if (roles.isEmpty()) {
            throw new BusinessException(ApiResult.ILLEGAL_PARAMS, "至少有一个角色");
        }
        Admin admin = new Admin();
        Date now = new Date();
        admin.setCreateDate(now);
        admin.setModifyDate(now);
        admin.setUsername(param.getUsername());
        admin.setPassword(DigestUtils.md5Hex(param.getPwd().getBytes()));
        admin.setRoles(new HashSet<>(roles));
        admin.setEnabled(param.isEnabled());
        admin.setPhone(param.getPhone());
        admin.setEmail(param.getEmail());
        admin.setName(param.getName());
        adminRepository.save(admin);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(Long[] ids) throws BusinessException {
        adminRepository.delete(adminRepository.findAll(Arrays.asList(ids)));
        if (adminRepository.count() == 0) {
            throw new BusinessException(ApiResult.ILLEGAL_PARAMS, "请至少保留一个管理员");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) throws BusinessException {
        Admin admin = adminRepository.findOne(id);
        adminRepository.delete(admin);
        if (adminRepository.count() == 0) {
            throw new BusinessException(ApiResult.ILLEGAL_PARAMS, "请至少保留一个管理员");
        }
    }
}

